/*
package com.ruoyi.security.config;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.security.domain.*;
import com.ruoyi.security.domain.vo.ElevatorRealDataVo;
import com.ruoyi.security.domain.vo.ElevatorStatusPushVo;
import com.ruoyi.security.domain.vo.ElevatorStatusVo;
import com.ruoyi.security.elevator.mqtt.MqttGateway;
import com.ruoyi.security.elevator.util.ElevatorDataValue;
import com.ruoyi.security.service.IAfElevatorErrorService;
import com.ruoyi.security.service.IAfElevatorInfoService;
import com.ruoyi.security.service.IAfElevatorService;
import com.ruoyi.system.api.RemoteMsgSendService;
import com.ruoyi.system.api.domain.SysMsgAndTemplate;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.java_websocket.client.WebSocketClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import javax.annotation.Resource;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class MqttInBoundConfiguration {
    @Resource
    private MqttConfiguration mqttProperties;

    //==================================== 消费消息==========================================//

    */
/**
     * 入站通道
     *
     * @return 消息通道对象 {@link MessageChannel}
     *//*

    @Bean("input")
    public MessageChannel mqttInputChannel() {
        //直连通道
        return new DirectChannel();
    }


    */
/**
     * 创建MqttPahoClientFactory 设置MQTT的broker的连接属性 如果使用ssl验证 也需要此处设置
     *
     * @return MQTT客户端工厂 {@link MqttPahoClientFactory}
     *//*

    @Bean
    public MqttPahoClientFactory inClientFactory() {
        //设置连接属性
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(mqttProperties.getUris());
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        options.setConnectionTimeout(mqttProperties.getTimeout());
        options.setKeepAliveInterval(mqttProperties.getKeepalive());
        // 接受离线消息  告诉代理客户端是否要建立持久会话   false为建立持久会话
        options.setCleanSession(false);
        //设置断开后重新连接
        options.setAutomaticReconnect(true);
        factory.setConnectionOptions(options);
        return factory;
    }


    */
/**
     * 入站
     *
     * @return 消息提供者 {@link MessageProducer}
     *//*

    @Bean
    public MessageProducer producer() {
        // Paho客户端消息驱动通道适配器，主要用来订阅主题  对inboundTopics主题进行监听
        //clientId 加后缀 不然会报retrying 不能重复
        String[] topics = {"elevator_test"};

        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(mqttProperties.getClientId()+System.currentTimeMillis(), inClientFactory(), topics);
        adapter.setCompletionTimeout(5000);
        // Paho消息转换器
        DefaultPahoMessageConverter defaultPahoMessageConverter = new DefaultPahoMessageConverter();
        // 按字节接收消息
        // defaultPahoMessageConverter.setPayloadAsBytes(true);
        adapter.setConverter(defaultPahoMessageConverter);
        // 设置QoS
        adapter.setQos(mqttProperties.getQos());
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    */
/**
     * 通过通道获取数据
     * ServiceActivator注解表明：当前方法用于处理MQTT消息，inputChannel参数指定了用于消费消息的channel。
     * tips:
     * 异步处理
     *
     * @return 消息处理 {@link MessageHandler}
     *//*

    @Bean
    @ServiceActivator(inputChannel = "input")
    public MessageHandler handler() {
        return message -> {
            log.info("收到的完整消息为--->{}", message);
            log.info("----------------------");
            log.info("message:" + message.getPayload());
            dealMessage(message.getPayload().toString());
            log.info("Id:" + message.getHeaders().getId());
            log.info("receivedQos:" + message.getHeaders().get(MqttHeaders.RECEIVED_QOS));
            String topic = (String) message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC);
            log.info("topic:" + topic);
            log.info("----------------------");
        };
    }


    @Autowired
    private RedisService redisService;
    @Autowired
    private IAfElevatorInfoService elevatorInfoService;
    @Autowired
    private IAfElevatorService elevatorService;


    @Autowired
    private MqttGateway mqttGateway;
    @Autowired
    private IAfElevatorErrorService afElevatorErrorService;
    @Autowired
    private RemoteMsgSendService remoteMsgSendService;


    private void dealMessage(String s){
        ElevatorResult<ElevatorData> result = JSON.parseObject(s, new TypeReference<ElevatorResult<ElevatorData>>() {});
        if (result.getErrorCode().equals("0") && result.getMsgType().equals("THIRDPARTY_REALTIME_DATA_RSP")) {
            if (result.getData() == null){
                return;
            }
            String regCode = result.getData().getRegisterCode();
            String eles = redisService.getCacheObject(regCode);
            if (StringUtils.isBlank(eles)){
                AfElevatorInfo param = new AfElevatorInfo();
                param.setRegisterCode(regCode);
                List<AfElevatorInfo> list = elevatorInfoService.selectAfElevatorInfoList(param);
                if (list.size() > 0 ){
                    AfElevatorInfo elevatorInfo = list.get(0);
                    ElevatorRealDataVo realDataVo = new ElevatorRealDataVo();
                    realDataVo.setElevatorInfo(elevatorInfo);
                    RealTimeData realTimeData = result.getData().getRealTimeData();
                    realDataVo.setRealTimeData(realTimeData);
                    redisService.setCacheObject(regCode, JSON.toJSONString(realDataVo));
                    ElevatorStatusVo statusVo = new ElevatorStatusVo();
                    statusVo.setElevId(elevatorInfo.getElevId());
                    statusVo.setId(elevatorInfo.getElevatorId());
                    statusVo.setErrorCode(realTimeData.get电梯故障代码());
                    statusVo.setNetStatus(realTimeData.get串口通信异常());
                    statusVo.setRepairStatus(realTimeData.get检修状态());
                    statusVo.setStatus(realTimeData.get故障状态());
                    redisService.setCacheObject(statusVo.getId(), JSON.toJSONString(statusVo));
                    mqttGateway.sendToMqtt("elevator_realData",JSON.toJSONString(realDataVo));
                    checkStatusAndPush(statusVo, realTimeData);
                }
            }else {
                ElevatorRealDataVo realDataVo = JSON.parseObject(eles, ElevatorRealDataVo.class);
                RealTimeData realTimeData = result.getData().getRealTimeData();
                realDataVo.setRealTimeData(realTimeData);
                redisService.setCacheObject(regCode, JSON.toJSONString(realDataVo));
                ElevatorStatusVo statusVo = new ElevatorStatusVo();

                statusVo.setElevId(realDataVo.getElevatorInfo().getElevId());
                statusVo.setId(realDataVo.getElevatorInfo().getElevatorId());
                statusVo.setErrorCode(realTimeData.get电梯故障代码());
                statusVo.setNetStatus(realTimeData.get串口通信异常());
                statusVo.setRepairStatus(realTimeData.get检修状态());
                statusVo.setStatus(realTimeData.get故障状态());
                statusVo.setDate(DateUtil.formatDateTime(new Date()));
                redisService.setCacheObject(statusVo.getId(), JSON.toJSONString(statusVo));
                mqttGateway.sendToMqtt("elevator_realData",JSON.toJSONString(realDataVo));
                checkStatusAndPush(statusVo, realTimeData);
            }
        }
    }



    private void checkStatusAndPush(ElevatorStatusVo statusVo, RealTimeData realTimeData){
        if (!statusVo.getStatus().equals("正常") || !statusVo.getNetStatus().equals("正常") || !statusVo.getRepairStatus().equals("正常")){
            // 推送消息
            // 查询电梯信息并推送到手机端
            String id = statusVo.getId();
            AfElevator result = elevatorService.selectAfElevatorById(id);
            if (result != null){
                ElevatorStatusPushVo pushVo = new ElevatorStatusPushVo();
                pushVo.setElevator(result);
                pushVo.setElevatorStatus(statusVo);
                mqttGateway.sendToMqtt("elevator_error", JSON.toJSONString(pushVo));
                //保存故障信息
                AfElevatorError error = new AfElevatorError();
                error.setElevatorId(statusVo.getId());
                error.setElevId(statusVo.getElevId());
                error.setErrorCode(statusVo.getErrorCode());
                if (!statusVo.getNetStatus().equals("正常")){
                    error.setErrorDesc("串口通信异常");
                }
                if (!statusVo.getStatus().equals("正常")){
                    error.setErrorDesc("故障报警");
                }
                if(!statusVo.getRepairStatus().equals("正常")){
                    error.setErrorDesc("检修");
                }
                error.setErrorMsg(JSON.toJSONString(realTimeData));
                afElevatorErrorService.insertErrorMsg(error);
                statusVo.setErrorId(error.getId());
                ElevatorDataValue.errorList = ElevatorDataValue.errorList.stream().filter(o -> !o.getId().equals(statusVo.getId())).collect(Collectors.toList());
                ElevatorDataValue.errorList.add(statusVo);
                //存入消息
                // 插入消息表，发送人
                SysMsgAndTemplate sysMsgSend = new SysMsgAndTemplate();
                sysMsgSend.setModuleType("电梯管理");
                sysMsgSend.getParamList().add(result.getElevatorCode());
                sysMsgSend.getParamList().add(error.getErrorDesc());
                //sysMsgSend.setTemplateType(msgTemplate.getTempType());
                //sysMsgSend.setUserId(userId);
                //插入log数据库
                remoteMsgSendService.insertMsg(sysMsgSend);
            }
        }else {
            // 移除故障列表
            //ElevatorDataValue.errorList = ElevatorDataValue.errorList.stream().filter( o -> !o.getId().equals(statusVo.getId())).collect(Collectors.toList());
            for (int i = ElevatorDataValue.errorList.size() - 1; i >= 0; i--){
                if (ElevatorDataValue.errorList.get(i).getId().equals(statusVo.getId())){
                    //更新故障时长
                    AfElevatorError error = new AfElevatorError();
                    error.setId(ElevatorDataValue.errorList.get(i).getErrorId());
                    error.setErrorTime(DateUtils.getNowDate().getTime()-DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,ElevatorDataValue.errorList.get(i).getDate()).getTime());
                    afElevatorErrorService.updateAfElevatorError(error);
                    ElevatorDataValue.errorList.remove(i);
                }
            }
            //移除离线列表
        }

    }



}
*/
